<template>
  <div class="work-layout">
    <a-spin class="spin-loading" v-if="loading" tip="加载中..." size="large" />
    <div class="work-tools">
      <a-button type="primary" @click="showDrawer('')" :icon="h(PlusOutlined)">新增任务</a-button>
      <a-dropdown :trigger="['click']">
        <a-button type="primary" :icon="h(SettingOutlined)" @click="closeStatus">看板配置</a-button>
        <template #overlay>
          <a-menu>
            <a-menu-item><a-checkbox v-model:checked="consfig.isTitle">标题</a-checkbox></a-menu-item>
            <a-menu-item><a-checkbox v-model:checked="consfig.isStatus">状态</a-checkbox></a-menu-item>
            <a-menu-item><a-checkbox v-model:checked="consfig.isPriority">优先级</a-checkbox></a-menu-item>
            <a-menu-item><a-checkbox v-model:checked="consfig.isCompletedTime">完成时间</a-checkbox></a-menu-item>
            <a-menu-item><a-checkbox v-model:checked="consfig.isDueDate">截至时间</a-checkbox></a-menu-item>
          </a-menu>
        </template>
      </a-dropdown>
      <a-button type="primary" :icon="h(SearchOutlined)" @click="openModal = true">搜索</a-button>
      <a-button type="primary" :icon="h(PlusOutlined)" @click="addPriorityHandler">新增优先级</a-button>
      <a-button type="primary" :icon="h(PlusOutlined)" @click="addStatusHandler">新增状态</a-button>
    </div>
    <div class="work-content">
      <div class="work-item" v-for="item in statusList" :key="item.id">
        <div class="title">
          <span>
            <span class="title-inner" :style="{backgroundColor: item.color}">{{ item.name }}</span>
            <span class="title-count" style="font-size: 14px;font-weight: 400;">{{ item.list.length }}</span>
          </span>
          <em class="icon-list">
            <PlusOutlined @click="showDrawer(item)"/>
            <a-dropdown :trigger="['click']">
              <EllipsisOutlined />
              <template #overlay>
                <a-menu>
                  <a-menu-item key="3" :icon="h(DeleteOutlined)" @click="removeGroup(item)">删除分组</a-menu-item>
                  <a-menu-item key="3" :icon="h(EditOutlined)" @click="editGroup(item)">编辑分组</a-menu-item>
                </a-menu>
              </template>
            </a-dropdown>
          </em>
        </div>
        <div class="content">
          <VueDraggable
            class="draggable-container"
            v-model="item.list"
            :animation="150"
            ghostClass="ghost"
            group="people"
            @update="onUpdate"
            @add="(value) => onAdd(value, item)"
            @remove="remove"
          >
            <WorkItem 
              :list="item.list" 
              :priorityList="priorityList" 
              :statusList="statusList" 
              :config="consfig" 
              :open="openWorkItem"
              :delHandler="delHandler"
              />
          </VueDraggable>
        </div>
      </div>
    </div>
    <a-drawer :width="1000" :title="title" :open="open" @close="onClose">
      <a-form :model="formData" :label-col="{ span: 4 }" :rules="rules" ref="formRef">
        <a-form-item label="任务名称" name="title" >
          <a-input v-model:value="formData.title" />
        </a-form-item>
        <a-form-item label="完成时间" name="completedTime">
          <a-date-picker v-model:value="formData.completedTime" format="YYYY-MM-DD" placeholder="请选择完成时间" />
        </a-form-item>
        <a-form-item label="优先级" name="priority" >
          <a-select v-model:value="formData.priority">
            <a-select-option :value="priority.id" v-for="priority in priorityList" :key="priority.id" style="display: flex;">
              <i class="select-color" :style="{backgroundColor: priority.color}"></i>
              {{ priority.name }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="任务状态" name="statusId" >
          <a-select v-model:value="formData.statusId">
            <a-select-option :value="statusItem.id" v-for="statusItem in statusList" :key="statusItem.id">
              <i class="select-color" :style="{backgroundColor: statusItem.color}"></i>
              {{ statusItem.name }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="截至日期" name="dueDate" >
          <a-date-picker v-model:value="formData.dueDate" format="YYYY-MM-DD" placeholder="请选择截至日期" />
        </a-form-item>
        <a-form-item label="任务描述" name="description">
          <div style="border: 1px solid #ccc">
          <Toolbar
            style="border-bottom: 1px solid #ccc"
            :editor="editorRef"
            :defaultConfig="{}"
            mode="default"
          />
          <Editor
            style="height: 301px; overflow-y: hidden;"
            v-model="formData.description"
            :defaultConfig="editorConfig"
            mode="default"
            @onCreated="handleCreated"
          />
        </div>
        </a-form-item>
        <a-form-item :wrapper-col="{ offset: 5 }">
          <a-button type="primary" html-type="submit" :icon="h(SaveOutlined)" @click="add(formRef)" :loading="subLoading">保存</a-button>
        </a-form-item>
      </a-form>
    </a-drawer>
    <a-modal v-model:open="openModal" title="搜索" @ok="handleOk" cancelText="取消" okText="搜索">
      <a-input-group compact>
        <a-select v-model:value="searchValue.flag" style="width: 100px" @change="selectChange">
          <a-select-option value="title">标题</a-select-option>
          <a-select-option value="statusId">状态</a-select-option>
          <a-select-option value="priority">优先级</a-select-option>
          <!-- <a-select-option value="dueDate">截至日期</a-select-option>
          <a-select-option value="completedTime">完成时间</a-select-option> -->
        </a-select>
        <a-input v-show="searchValue.flag === 'title'" style="width: 60%" v-model:value="searchValue.value" placeholder="请输入任务名称"/>
        <!-- 状态 -->
        <a-select v-show="searchValue.flag === 'statusId'" style="width: 60%" v-model:value="searchValue.value">
          <a-select-option :value="statusItem.id" v-for="statusItem in statusList" :key="statusItem.id">
            <i class="select-color" :style="{backgroundColor: statusItem.color}"></i>
            {{ statusItem.name }}
          </a-select-option>
        </a-select>
        <!-- 优先级 -->
        <a-select v-show="searchValue.flag === 'priority'" style="width: 60%" v-model:value="searchValue.value">
          <a-select-option :value="priority.id" v-for="priority in priorityList" :key="priority.id" style="display: flex;">
            <i class="select-color" :style="{backgroundColor: priority.color}"></i>
            {{ priority.name }}
          </a-select-option>
        </a-select>
      </a-input-group>
    </a-modal>
    <a-drawer :title="drawerTitle" placement="bottom" :closable="true" :open="openPriority" @close="priorityClose">
      <a-form :model="drawerForm" layout="inline" ref="drawerFormRef">
        <a-form-item label="名称" name="name" :rules="[{ required: true, message: '请输入名称' }]" >
          <a-input v-model:value="drawerForm.name"/>
        </a-form-item>
        <a-form-item label="颜色" name="color" :rules="[{ required: true, message: '请选择颜色' }]">
          <el-color-picker v-model="drawerForm.color" show-alpha :predefine="predefineColors" />
        </a-form-item>
        <a-form-item label="排序" name="orderNum" v-if="flag === Tag.STATUS || flag === Tag.EDIT">
          <a-input-number id="inputNumber" v-model:value="drawerForm.orderNum" :min="1" :max="1000" />
        </a-form-item>
        <a-form-item :wrapper-col="{ offset: 5 }">
          <a-button type="primary" html-type="submit" :icon="h(SaveOutlined)" :loading="subLoading" @click="subHandler(drawerFormRef)">保存</a-button>
        </a-form-item>
      </a-form>
  </a-drawer>
  </div>
</template>

<script setup lang="ts">
import { ref, h, shallowRef, onMounted } from 'vue';
import { VueDraggable } from "vue-draggable-plus";
import WorkItem from './WorkItem.vue';
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
import { FormInstance, message } from 'ant-design-vue';
import { deepClone } from '@/utils';
import dayjs from "dayjs";
import {
  PlusOutlined,
  EllipsisOutlined,
  DeleteOutlined,
  SettingOutlined,
  SearchOutlined,
  SaveOutlined,
  EditOutlined
} from '@ant-design/icons-vue';
import { 
  addPriority, 
  addStatus, 
  addTask, 
  delStak, 
  delWork, 
  editStatus, 
  getPriorityList, 
  getWorkAssignList, 
  getWorkList, 
  udpateTask 
} from '@/api/work-assign';

enum Tag {
  ADD = "ADD",
  EDIT = "EDIT",
  STATUS = "STATUS", // 状态
  PRIORITY = "PRIORITY" // 优先级
}

const initForm: any = {
  title: "", // 任务标题
  description: "", // 任务描述
  createdUserId: 0, // 创建用户
  completedTime: "", // 完成时间
  priority: "", // 优先级
  statusId: "", // 状态
  dueDate: "" // 截至日期
};
const initDrawerForm: any = {
  name: "", // 名称
  color: "rgba(30, 144, 255, 1)", // 颜色
  orderNum: 1
};
const searchValue = ref({
  flag: "title",
  value: ""
});
const drawerTitle = ref<string>("");
const openPriority = ref<boolean>(false);
const subLoading = ref<boolean>(false);
const loading = ref<boolean>(false);
const formRef = ref();
const drawerFormRef = ref();
const isSearch = ref<boolean>(false);
const openModal = ref<boolean>(false);
const title = ref<string>("新增任务");
const flag = ref<Tag>(Tag.ADD);
const open = ref<boolean>(false);
const priorityList = ref<any[]>([]);
const statusList = ref<any[]>([]);
const editorConfig: any = {
  placeholder: '请输入内容...',
  MENU_CONF: {
    uploadImage: {
      uploadImgShowBase64: true
    }
  }
}
const editorRef = shallowRef();
const formData = ref(deepClone(initForm));
const drawerForm = ref(deepClone(initDrawerForm));
const consfig = ref({
  isTitle: true,
  isStatus: true,
  isPriority: true,
  isCompletedTime: true,
  isDueDate: true
});
const rules = ref({
  title: [{ required: true, message: '请输入任务名称', trigger: 'blur' }],
  description: [],
  createdUserId: [],
  assignedPerson: [],
  createdTime: [],
  completedTime: [],
  priority: [{ required: true, message: '请输入任务优先级', trigger: 'blur' }],
  statusId: [{ required: true, message: '请输入任务状态', trigger: 'blur' }],
  dueDate: [{ required: true, message: '请输入任务截至日期', trigger: 'blur' }]
});
// 预制颜色
const predefineColors = ref([
  '#ff4500',
  '#ff8c00',
  '#ffd700',
  '#90ee90',
  '#00ced1',
  '#1e90ff',
  '#c71585',
  'rgba(255, 69, 0, 0.68)',
  'rgb(255, 120, 0)',
  'hsv(51, 100, 98)',
  'hsva(120, 40, 94, 0.5)',
  'hsl(181, 100%, 37%)',
  'hsla(209, 100%, 56%, 0.73)',
  '#c7158577',
]);


onMounted(() => {
  init();
});

const init = async () => {
  loading.value = true;
  try {
    initPriority();
  await initWorkAssign();
  initWorkData();
  } catch (error) {
    console.log(error);
  }finally {
    loading.value = false;
  }
};

// 初始化优先级
const initPriority = async () => {
  try {
    const result = await getPriorityList();
    priorityList.value = result.value;
  } catch (error) {
    console.log(error);
  }
};

/**
 * @description 初始化任务列表
 */
const initWorkAssign = async () => {
  try {
    const result = await getWorkAssignList();
    statusList.value = result.value;
    statusList.value.forEach((item: any) => {
      item.show = true;
      item.list = [];
    });
    statusList.value.sort((a, b) => a.orderNum - b.orderNum);
  } catch (error) {
    console.log(error);
  }
};

// 任务数据
const initWorkData = async () => {
  try {
    const result = await getWorkList();
    if (result && statusList.value.length > 0) {
      result.value.forEach((item: any) => {
        statusList.value.forEach(s => {
          if (s.id === item.statusId) {
            s.list.push(item);
          }
        })
      });
      return;
    }
    message.error(result.message);
  } catch (error) {
    console.log(error);
  }
};

const handleCreated = (editor: any) => {
  console.log(editor.getConfig());
  editorRef.value = editor;
}

// 打开任务详情
const openWorkItem = (item: any) => {
  title.value = "任务详情";
  flag.value = Tag.EDIT;
  formData.value = deepClone(item);
  formData.value.dueDate = formData.value.dueDate && dayjs(item.dueDate);
  formData.value.completedTime = formData.value.completedTime && dayjs(item.completedTime);
  open.value = true;
  closeStatus();
};

// 打开弹窗
const showDrawer = (cloumn?: any) => {
  title.value = "新增任务";
  flag.value = Tag.ADD;
  open.value = true;
  if(cloumn) {
    formData.value.statusId = cloumn.id;
  }
  closeStatus();
};

// 关门弹窗
const onClose = () => {
  clearForm();
  open.value = false;
};

// 关闭状态弹窗
const priorityClose = () => {
  openPriority.value = false;
  drawerForm.value = deepClone(initDrawerForm);
}

// 清空选择状态
const closeStatus = () => {
  if (!isSearch.value || statusList.value.length <= 0) return;
  isSearch.value = false;
  statusList.value.forEach((item: any) => {
    if (item.list && Array.isArray(item.list) && item.list.length > 0) {
      item.list.forEach( (i: any) => {
          i.show = false;
      })
    }
  })
};

// 新增优先级
const addPriorityHandler = () => {
  openPriority.value = true;
  flag.value = Tag.PRIORITY;
  drawerTitle.value = "新增优先级";
}

// 新增状态
const addStatusHandler = () => {
  openPriority.value = true;
  flag.value = Tag.STATUS;
  drawerTitle.value = "新增状态";
}

// 搜索切换方式清空起搜索内容
const selectChange = () => {
  searchValue.value.value = "";
};

// 搜索处理
const handleOk = () => {
  isSearch.value = true;
  statusList.value.forEach((item: any) => {
    item.list.forEach( (i: any) => {
      // 处理数字
      if (
        i[searchValue.value.flag] && 
        (typeof(i[searchValue.value.flag]) === "string" && 
        i[searchValue.value.flag].includes(searchValue.value.value)) || 
        (typeof(i[searchValue.value.flag]) === "number" && 
        i[searchValue.value.flag] === Number(searchValue.value.value))
      ) {
        i.show = true;
      } else {
        i.show = false;
      }
    })
  })
  openModal.value = false;
};

// 更新
function onUpdate(item: any) {
  try {
    closeStatus();
    // udpateTask(item.clonedData);
    console.log(item);
    
  } catch (error) {
    console.log(error);
    
  }
}

// 添加
function onAdd(value: any,item: any) {
  console.log(value, item);
  try {
    value.data.statusId = item.id;
    value.clonedData.statusId = item.id;
    udpateTask(value.clonedData);
  } catch (error) {
    console.log(error);
  }
  closeStatus();
}

const delHandler = async (item: any) => {
  loading.value = true;
  try {
    const result = await delWork(item.id);
    if (result.code === 200) {
      message.success("删除成功");
      init();
      return;
    }
    message.error(result.message);
  } catch (error) {
    console.log(error);
    message.error("删除失败");
  } finally {
    loading.value = true;
  }
};

// 移除
function remove(item: any) {
  // todo 处理失败的时候处理
  console.log('remove', item);
}

//新增
const add = (form: FormInstance | undefined) => {
  if (!form) return;
  form.validate().then(async () => {
      subLoading.value = true;
      if (flag.value === Tag.ADD){
        try {
          const params = {
            ...formData.value
          };
          params.dueDate = params.dueDate && dayjs(params.dueDate).format("YYYY-MM-DD");
          params.completedTime = params.completedTime && dayjs(params.completedTime).format("YYYY-MM-DD");
          const result = await addTask(params);
          if (result.code === 200) {
            message.success("新增成功");
            init();
            onClose();
            return;
          }
          message.error(result.message);
        } catch (error) {
          message.error("新增失败");
        }finally {
          subLoading.value = false;
        }
      } else {
        try {
          const result = await udpateTask(formData.value);
          if (result.code === 200) {
            message.success("更新成功");
            init();
            onClose();
            return;
          }
          message.error(result.message);
        } catch (error) {
          message.error("更新失败");
        } finally {
          subLoading.value = false;
        }
      }
    })
};

const subHandler = (form: FormInstance | undefined) => {
  if (!form) return;
  try {
    subLoading.value = true;
    form.validate().then(async () => {
      if (flag.value === Tag.STATUS) {
        try {
          const params = {
            ...drawerForm.value
          };
          const result = await addStatus(params);
          if (result.code === 200) {
            message.success("保存成功");
            init();
            priorityClose();
            return;
          }
          message.error(result.message);
        } catch (error) {
          message.error("保存失败，请稍后再试");
        }finally {
          subLoading.value = false;
        }
      }
      if (flag.value === Tag.PRIORITY) {
        try {
          const params = {
            ...drawerForm.value
          };
          delete params.orderNum;
          const result = await addPriority(params);
          if(result.code === 200) {
            message.success("保存成功");
            init();
            priorityClose();
            return;
          }
          message.error(result.message);
        } catch (error) {
          message.error("保存失败，请稍后再试");
        }finally {
          subLoading.value = false;
        }
      }
      if (flag.value === Tag.EDIT) {
        try {
          const params = {
            ...drawerForm.value
          };
          const result = await editStatus(params);
          if (result.code === 200) {
            message.success("保存成功");
            init();
            priorityClose();
            return;
          }
          message.error(result.message);
        } catch (error) {
          message.error("保存失败，请稍后再试");
        }finally {
          subLoading.value = false;
        }
      }
    })
  } catch (error) {
    message.error("保存失败，请稍后再试");
  }
};

// 删除分组
const removeGroup = async (item: any) => {
  try {
    loading.value = true;
    const result = await delStak(item.id);
    if(result.code === 200) {
      message.success("删除成功");
      init();
      return;
    }
    message.error(result.message);
  } catch (error) {
    message.error("删除失败");
  } finally {
    loading.value = false;
  }
};

const editGroup = (item: any) => {
  drawerForm.value = deepClone(item);
  openPriority.value = true;
  flag.value = Tag.EDIT;
};

// 清除表单数据
const clearForm = () => {
  formData.value = deepClone(initForm);
}
</script>

<style scoped lang="less">
.work-layout {
  width: 100%;
  height: 100%;
  background-color: #fafafa;
  position: relative;
  .spin-loading {
    position: absolute;
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;
    background-color: rgba(255, 255, 255, 0.7);
    z-index: 999;
  }
  .work-tools {
    padding: 0px 20px;
    height: 40px;
    display: flex;
    align-items: center;
    border-bottom: 1px solid #e7e9e8;
    .ant-btn {
      margin-right: 10px;
    }
  }
  .work-content {
    width: 100%;
    height: calc(100% - 40px);
    padding: 16px;
    display: -webkit-box;
    overflow-y: auto;
    .work-item {
      width: 296px;
      height: 100%;
      margin-right: 10px;
      border: 1px solid #e7e9e8;
      .title {
        width: 100%;
        height: 32px;
        padding: 0 4px;
        display: flex;
        align-items: center;
        justify-content: space-between;
        .title-inner {
          font-size: 16px;
          padding: 2px 6px;
          border-radius: 4px;
        }
        .title-count {
          margin-left: 4px;
          font-size: 12px;
          color: #8f9492;
        }
        span {
          font-size: 14px;
        }
        .icon-list {
          .anticon {
            margin-left: 10px;
          }
        }
      }
      .content {
        width: 100%;
        height: calc(100% - 32px);
        .draggable-container {
          width: 100%;
          height: 100%;
          overflow-y: auto;
          overflow-x: hidden;
        }
      }
    }
  }
}
</style>
